<script setup name="Menu" lang="ts">
import { DeleteOutlined, FormOutlined, PlusSquareOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue'
import { addMenu, delMenu, getMenu, listMenu, updateMenu } from '@/api/system/menu'
import type { MenuForm, MenuQuery, MenuVO } from '@/api/system/menu/types'
import { MenuTypeEnum } from '@/enums/MenuTypeEnum'

interface MenuOptionsType {
  menuId: number
  menuName: string
  children: MenuOptionsType[] | undefined
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { sys_show_hide, sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_show_hide', 'sys_normal_disable'))
const message = useMessage()
const modal = useModal()
const menuList = ref<MenuVO[]>([])
const loading = ref(true)
const menuOptions = ref<MenuOptionsType[]>([])
const isExpandAll = ref(true)

const expandRows = ref<string[] | number[]>([])

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

const queryFormRef = ref()
const menuFormRef = ref()
const initFormData = {
  path: '',
  menuId: undefined,
  parentId: 0,
  menuName: '',
  icon: '',
  menuType: MenuTypeEnum.M,
  orderNum: 1,
  isFrame: '1',
  isCache: '0',
  visible: '0',
  status: '0',
}
const data = reactive<PageData<MenuForm, MenuQuery>>({
  form: { ...initFormData },
  queryParams: {
    menuName: undefined,
    status: undefined,
  },
  rules: {
    menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
    orderNum: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }],
    path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
  },
})

const menuTableRef = ref<ElTableInstance>()

const { queryParams, form, rules } = toRefs<PageData<MenuForm, MenuQuery>>(data)

/** 查询菜单列表 */
async function getList() {
  loading.value = true
  const res = await listMenu(queryParams.value)
  const data = proxy?.handleTree<MenuVO>(res.data, 'menuId')
  if (data)
    menuList.value = data

  loading.value = false
}

/** 查询菜单下拉树结构 */
async function getTreeselect() {
  menuOptions.value = []
  const response = await listMenu()
  const menu: MenuOptionsType = { menuId: 0, menuName: '主类目', children: [] }
  menu.children = proxy?.handleTree<MenuOptionsType>(response.data, 'menuId')
  menuOptions.value.push(menu)
}

/** 取消按钮 */
function cancel() {
  reset()
  dialog.visible = false
}

/** 表单重置 */
function reset() {
  form.value = { ...initFormData }
  menuFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row?: MenuVO) {
  reset()
  getTreeselect()
  row && row.menuId ? form.value.parentId = row.menuId : form.value.parentId = 0
  form.value.permType = 1 // 默认为操作权限。1 操作权限，2 查看权限
  dialog.visible = true
  dialog.title = '添加菜单'
}

/** 展开/折叠操作 */
function handleToggleExpandAll() {
  isExpandAll.value = !isExpandAll.value
  expandRows.value = []
  toggleExpandAll(menuList.value, isExpandAll.value)
}

/** 展开/折叠所有 */
function toggleExpandAll(data: MenuVO[], status: boolean) {
  data.forEach((item) => {
    if (status)
      expandRows.value.push(item.menuId)
    if (item.children)
      toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
async function handleUpdate(row: MenuVO) {
  reset()
  await getTreeselect()
  if (row.menuId) {
    const { data } = await getMenu(row.menuId)
    form.value = data
  }
  dialog.visible = true
  dialog.title = '修改菜单'
}

/** 提交按钮 */
function submitForm() {
  menuFormRef.value?.validate().then(async () => {
    form.value.menuId ? await updateMenu(form.value) : await addMenu(form.value)
    message.success('操作成功')
    dialog.visible = false
    await getList()
  })
}

/** 删除按钮操作 */
async function handleDelete(row: MenuVO) {
  modal.confirm({
    title: `是否确认删除名称为"${row.menuName}"的数据项?`,
    onOk: async () => {
      await delMenu(row.menuId)
      await getList()
      message.success('删除成功')
    },
  })
}

onMounted(async () => {
  await getList()
})
</script>

<template>
  <div class="p-2">
    <a-card shadow="hover" class="mb-20px">
      <div class="flex-between">
        <div>
          <a-form ref="queryFormRef" class="inline-form" :model="queryParams" layout="inline" label-width="68px">
            <a-form-item label="菜单名称" prop="menuName">
              <a-input
                v-model:value="queryParams.menuName" placeholder="请输入菜单名称" allow-clear style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="状态" prop="status">
              <a-select v-model:value="queryParams.status" style="width: 200px" placeholder="菜单状态" allow-clear>
                <a-select-option
                  v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                  :value="dict.value"
                >
                  {{ dict.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button class="mr-10px" type="primary" @click="handleQuery">
                搜索
              </a-button>
              <a-button @click="resetQuery">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <a-row :gutter="10">
            <a-col :span="1.5">
              <a-button v-hasPermi="['system:menu:add']" type="primary" @click="handleAdd()">
                新增
              </a-button>
            </a-col>
            <a-col :span="1.5">
              <a-button @click="handleToggleExpandAll">
                展开/折叠
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-card>
    <a-card shadow="hover">
      <a-table
        ref="menuTableRef"
        v-model:expandedRowKeys="expandRows"
        :loading="loading"
        :data-source="menuList"
        :pagination="false"
        row-key="menuId"
        :default-expand-all-rows="isExpandAll"
      >
        <a-table-column data-index="menuName" title="菜单名称" :ellipsis="true" width="160" />
        <a-table-column data-index="icon" title="图标" align="center" width="100">
          <template #default="{ record }">
            <bh-icon :name="record.icon" />
          </template>
        </a-table-column>
        <a-table-column data-index="orderNum" title="排序" width="60" />
        <a-table-column data-index="perms" title="权限标识" :ellipsis="true" />
        <a-table-column data-index="component" title="组件路径" :ellipsis="true" />
        <a-table-column data-index="status" title="状态" width="80">
          <template #default="{ record }">
            <dict-tag :options="sys_normal_disable" :value="record.status" />
          </template>
        </a-table-column>
        <a-table-column title="创建时间" align="center" data-index="createTime">
          <template #default="{ record }">
            <span>{{ record.createTime }}</span>
          </template>
        </a-table-column>
        <a-table-column fixed="right" title="操作" width="180">
          <template #default="{ record }">
            <a-tooltip title="修改" placement="top">
              <a-button v-hasPermi="['system:menu:edit']" type="link" @click="handleUpdate(record)">
                <FormOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip title="新增" placement="top">
              <a-button v-hasPermi="['system:menu:add']" type="link" @click="handleAdd(record)">
                <PlusSquareOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip title="删除" placement="top">
              <a-button
                v-hasPermi="['system:menu:remove']" type="link"
                @click="handleDelete(record)"
              >
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>
    </a-card>

    <a-modal v-model:open="dialog.visible" :mask-closable="false" :keyboard="false" :title="dialog.title" destroy-on-close append-to-bod width="750px">
      <a-form ref="menuFormRef" :model="form" :rules="rules" :label-col="{ style: 'width:100px' }">
        <a-row>
          <a-col :span="24">
            <a-form-item label="上级菜单">
              <a-tree-select
                v-model:value="form.parentId"
                :tree-data="menuOptions"
                tree-default-expand-all
                :field-names="{ value: 'menuId', label: 'menuName', children: 'children' }"
                placeholder="选择上级菜单"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="菜单类型" prop="menuType">
              <a-radio-group v-model:value="form.menuType">
                <a-radio value="M">
                  目录
                </a-radio>
                <a-radio value="C">
                  菜单
                </a-radio>
                <a-radio value="F">
                  按钮
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="form.menuType !== 'F'" :span="24">
            <a-form-item label="菜单图标" prop="icon">
              <!-- 图标选择器 -->
              <a-input v-model:value="form.icon" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="菜单名称" prop="menuName">
              <a-input v-model:value="form.menuName" placeholder="请输入菜单名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="显示排序" prop="orderNum">
              <a-input-number v-model:value="form.orderNum" :controls="false" style="width: 100%" controls-position="right" :min="0" />
            </a-form-item>
          </a-col>
          <a-col v-if="form.menuType !== 'F'" :span="12">
            <a-form-item>
              <template #label>
                <span>
                  <a-tooltip title="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                    <QuestionCircleOutlined /> </a-tooltip>是否外链
                </span>
              </template>
              <a-radio-group v-model:value="form.isFrame">
                <a-radio value="0">
                  是
                </a-radio>
                <a-radio value="1">
                  否
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="form.menuType !== 'F'" :span="12">
            <a-form-item prop="path">
              <template #label>
                <span>
                  <a-tooltip
                    title="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
                    placement="top"
                  >
                    <QuestionCircleOutlined />
                  </a-tooltip>
                  路由地址
                </span>
              </template>
              <a-input v-model:value="form.path" placeholder="请输入路由地址" />
            </a-form-item>
          </a-col>
          <a-col v-if="form.menuType === 'C'" :span="12">
            <a-form-item prop="component">
              <template #label>
                <span>
                  <a-tooltip title="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                    <QuestionCircleOutlined />
                  </a-tooltip>
                  组件路径
                </span>
              </template>
              <a-input v-model:value="form.component" placeholder="请输入组件路径" />
            </a-form-item>
          </a-col>
          <a-col v-if="form.menuType !== 'M'" :span="12">
            <a-form-item>
              <a-input v-model:value="form.perms" placeholder="请输入权限标识" maxlength="100" />
              <template #label>
                <span>
                  <a-tooltip title="控制器中定义的权限字符，如：@SaCheckPermission('system:user:list')" placement="top">
                    <QuestionCircleOutlined />
                  </a-tooltip>
                  权限字符
                </span>
              </template>
            </a-form-item>
          </a-col>
          <a-col v-if="form.menuType === 'C'" :span="12">
            <a-form-item>
              <a-input v-model:value="form.queryParam" placeholder="请输入路由参数" maxlength="255" />
              <template #label>
                <span>
                  <a-tooltip
                    title="访问路由的默认传递参数，如：`{&quot;id&quot;: 1, &quot;name&quot;: &quot;ry&quot;}`"
                    placement="top"
                  >
                    <QuestionCircleOutlined />
                  </a-tooltip>
                  路由参数
                </span>
              </template>
            </a-form-item>
          </a-col>
          <a-col v-if="form.menuType === 'C'" :span="12">
            <a-form-item>
              <template #label>
                <span>
                  <a-tooltip title="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                    <QuestionCircleOutlined />
                  </a-tooltip>
                  是否缓存
                </span>
              </template>
              <a-radio-group v-model:value="form.isCache">
                <a-radio value="0">
                  缓存
                </a-radio>
                <a-radio value="1">
                  不缓存
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="form.menuType !== 'F'" :span="12">
            <a-form-item>
              <template #label>
                <span>
                  <a-tooltip title="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                    <QuestionCircleOutlined />
                  </a-tooltip>
                  显示状态
                </span>
              </template>
              <a-radio-group v-model:value="form.visible">
                <a-radio v-for="dict in sys_show_hide" :key="dict.value" :value="dict.value" :label="dict.value">
                  {{ dict.label }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item>
              <template #label>
                <span>
                  <a-tooltip title="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                    <QuestionCircleOutlined />
                  </a-tooltip>
                  菜单状态
                </span>
              </template>
              <a-radio-group v-model:value="form.status">
                <a-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value" :label="dict.value">
                  {{ dict.label }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="form.menuType === MenuTypeEnum.F" :span="12">
            <a-form-item label="权限类型">
              <a-radio-group v-model:value="form.permType">
                <a-radio :value="1">
                  操作权限
                </a-radio>
                <a-radio :value="2">
                  查看权限
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button type="primary" @click="submitForm">
            确 定
          </a-button>
          <a-button @click="cancel">
            取 消
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
